﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;

namespace MadPropsDemo.RecipeEditor.Model
{
    class SimpleRecipeService : IRecipeService
    {
        static readonly DataContractJsonSerializer serializer =
            new DataContractJsonSerializer(typeof(RecipeDTO));

        public void Save(RecipeDTO recipe, string filename)
        {
            if (string.IsNullOrWhiteSpace(recipe.Name))
            {
                throw new Exception("Recipe name is required");
            }

            using (var stream = OpenWrite(filename))
            {
                serializer.WriteObject(stream, recipe);
            }
        }

        public RecipeDTO Load(string filename)
        {
            using (var stream = OpenRead(filename))
            {
                var recipe = serializer.ReadObject(stream);
                return (RecipeDTO)recipe;
            }
        }

        protected virtual Stream OpenWrite(string filename)
        {
            return File.OpenWrite(filename);
        }

        protected virtual Stream OpenRead(string filename)
        {
            return File.OpenRead(filename);
        }
    }
}
